<template>
  <div class="user-list-container">
    <!-- 搜索和操作栏 -->
    <div class="action-bar">
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="请输入用户名或邮箱搜索"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
      <div class="operation-area">
        <el-button 
          type="primary" 
          @click="handleAdd"
          v-if="currentUser?.is_superuser || currentUser?.is_admin"
        >
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <el-table
      v-loading="loading"
      :data="userList"
      style="width: 100%"
      border
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="username" label="用户名" min-width="120" />
      <el-table-column prop="email" label="邮箱" min-width="180" />
      <el-table-column prop="role" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="row.is_superuser ? 'danger' : row.is_admin ? 'warning' : 'info'">
            {{ getRoleName(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="last_login" label="最后登录时间" min-width="180">
        <template #default="{ row }">
          {{ formatDate(row.last_login) }}
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.is_active ? 'success' : 'danger'">
            {{ row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button 
              type="primary" 
              link 
              @click="handleEdit(row)"
              v-if="canEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleToggleStatus(row)"
              v-if="canToggleStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="danger" 
              link
              @click="handleDelete(row)"
              v-if="canDelete(row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role" v-if="!userForm.isCurrentUser">
          <el-select v-model="userForm.role" class="w-full">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
            <el-option label="超级管理员" value="superuser" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" v-else>
          <el-tag :type="userForm.role === 'superuser' ? 'danger' : userForm.role === 'admin' ? 'warning' : 'info'">
            {{ userForm.role === 'superuser' ? '超级管理员' : userForm.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api/user'

// 状态定义
const loading = ref(false)
const userList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const currentUser = ref(null)

// 表单数据
const userForm = ref({
  username: '',
  email: '',
  password: '',
  role: 'user'
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value
    }
    const res = await userApi.getUserList(params)
    if (res.status === 'success') {
      userList.value = res.data
      total.value = res.total
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    ElMessage.error(error.response?.data?.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 角色名称转换
const getRoleName = (user) => {
  if (user.is_superuser) return '超级管理员'
  if (user.is_admin) return '管理员'
  return '普通用户'
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  if (!canEdit(row)) {
    ElMessage.error('您没有权限执行此操作')
    return
  }
  dialogType.value = 'edit'
  userForm.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    role: row.is_superuser ? 'superuser' : row.is_admin ? 'admin' : 'user',
    isCurrentUser: row.id === currentUser.value?.id
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          const userData = {
            username: userForm.value.username,
            email: userForm.value.email,
            password: userForm.value.password,
            name: userForm.value.username,  // 使用username作为默认name
            gender: 'M',  // 默认性别为男
            is_admin: userForm.value.role === 'admin',
            is_superuser: userForm.value.role === 'superuser'
          }
          const res = await userApi.createUser(userData)
          if (res.status === 'success' || res.message === '注册成功') {
            ElMessage.success('添加用户成功')
            dialogVisible.value = false
            fetchUserList()
          } else {
            ElMessage.error(res.message || '添加用户失败')
          }
        } else {
          // 如果是编辑自己，不允许修改角色
          const updateData = {
            username: userForm.value.username,
            email: userForm.value.email,
            name: userForm.value.username,  // 使用username作为name
            is_admin: userForm.value.role === 'admin',
            is_superuser: userForm.value.role === 'superuser'
          }
          await userApi.updateUser(userForm.value.id, updateData)
          ElMessage.success('更新用户成功')
          dialogVisible.value = false
          fetchUserList()
        }
      } catch (error) {
        console.error('操作失败:', error)
        if (error.response?.data?.errors) {
          const errors = error.response.data.errors
          Object.keys(errors).forEach(key => {
            ElMessage.error(`${key}: ${errors[key].join(', ')}`)
          })
        } else {
          ElMessage.error(error.response?.data?.message || (dialogType.value === 'add' ? '添加用户失败' : '更新用户失败'))
        }
      }
    }
  })
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  if (!canToggleStatus(row)) {
    ElMessage.error('您没有权限执行此操作')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await userApi.toggleUserStatus(row.id)
    ElMessage.success(`${row.is_active ? '禁用' : '启用'}用户成功`)
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${row.is_active ? '禁用' : '启用'}用户失败`)
    }
  }
}

// 删除用户
const handleDelete = async (row) => {
  if (!canDelete(row)) {
    ElMessage.error('您没有权限执行此操作')
    return
  }
  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await userApi.deleteUser(row.id)
    ElMessage.success('删除用户成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  userForm.value = {
    username: '',
    email: '',
    password: '',
    role: 'user'
  }
}

// 初始化
onMounted(() => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    currentUser.value = JSON.parse(userStr)
  }
  fetchUserList()
})

// 权限控制函数
const canEdit = (user) => {
  if (!currentUser.value) return false
  // 超级管理员可以编辑所有用户
  if (currentUser.value.is_superuser) return true
  // 管理员只能编辑普通用户
  if (currentUser.value.is_admin && !user.is_superuser && !user.is_admin) return true
  return false
}

const canToggleStatus = (user) => {
  if (!currentUser.value) return false
  // 超级管理员不能禁用自己
  if (currentUser.value.is_superuser && user.id === currentUser.value.id) return false
  // 超级管理员可以禁用/启用其他所有用户
  if (currentUser.value.is_superuser) return true
  // 管理员只能禁用/启用普通用户
  if (currentUser.value.is_admin && !user.is_superuser && !user.is_admin) return true
  return false
}

const canDelete = (user) => {
  if (!currentUser.value) return false
  // 超级管理员不能删除自己
  if (currentUser.value.is_superuser && user.id === currentUser.value.id) return false
  // 超级管理员可以删除所有非超级管理员用户
  if (currentUser.value.is_superuser && !user.is_superuser) return true
  return false
}
</script>

<style scoped>
.user-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  gap: 16px;
}

.search-area {
  display: flex;
  gap: 8px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  flex: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.w-full {
  width: 100%;
}
</style> 